class UnionFind:
    def __init__(self, length=0):
        self._p = [i for i in range(length)]
        self._length = length

    def union(self, i, j):
        p_i, p_j = self.parent(i), self.parent(j)
        self._p[p_i] = p_j

    def parent(self, i):
        root = i
        while self._p[root] != root: root = self._p[root]
        
        while self._p[i] != i:
            x = i
            i = self._p[i]
            self._p[x] = root
        return root

    def sum(self):
        return sum(self._p[i] == i for i in range(self._length))

class Solution:
    def findCircleNum(self, isConnected):
        if not isConnected or not isConnected[0]:
            return 0

        rows = len(isConnected)
        u = UnionFind(rows)

        for i in range(rows):
            for j in range(1, rows):
                if isConnected[i][j] == 1:
                    u.union(i, j)

        return u.sum()



if __name__ == '__main__':
    isConnected = [[1,1,0],[1,1,0],[0,0,1]]
    print(Solution().findCircleNum(isConnected))
    